package com.szgd.service.hiddenDanger;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.szgd.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.szgd.bean.HiddenDanger;
import com.szgd.dao.ecdata.hiddenDanger.HiddenDangerMapper;
import com.szgd.dao.ecdata.sys.WfRoleMapper;
import com.szgd.paging.Order;
import com.szgd.paging.PageBounds;
import com.szgd.service.personnel.AttachService;
import com.szgd.service.project.SiteService;
import com.szgd.service.sys.SimulateBaseService;
import com.szgd.service.sys.SysDictService;
import com.szgd.service.sys.UserService;
import com.szgd.service.weixin.WeChatService;

@Service
public class HiddenDangerService extends SimulateBaseService {

    @Autowired
    HiddenDangerMapper hiddenDangerMapper;
    @Autowired
    WfRoleMapper wfRoleMapper;
    @Autowired
    AttachService attachService;
    @Autowired
    WeChatService weChatService;
    @Autowired
    SysDictService sysDictService;
    @Autowired
    SiteService siteService;
    @Autowired
    UserService userService;
    @Autowired
    FileUtil fileUtil;

    public void setTaskCount(HttpSession httpSession,String roleIds) {
        if (roleIds != null && roleIds.indexOf("hidden_danger_approver") >=0)
        {
            Map<String, Object> params = new HashMap<>();
            params.put("approveFlag",1);
            httpSession.setAttribute("taskCount",hiddenDangerMapper.getHiddenDangerCount(params));
        }else if (roleIds != null && roleIds.indexOf("hidden_danger_confirmer") >=0)
        {
            Map<String, Object> params = new HashMap<>();
            params.put("approveFlag",2);
            httpSession.setAttribute("taskCount",hiddenDangerMapper.getHiddenDangerCount(params));
        }

    }

    public int getHiddenDangerCount(Map<String, Object> params) {
        return  hiddenDangerMapper.getHiddenDangerCount(params);
    }

    private void computeRectifyHours(List<Map<String,Object>> hiddenDangerList){
        for (int i = 0; i < hiddenDangerList.size(); i++) {
            Map<String, Object> hiddenMap = hiddenDangerList.get(i);
            String startTime = hiddenMap.get("beginTime")==null?"":hiddenMap.get("beginTime").toString();
            String endTime = hiddenMap.get("endTime")==null?"":hiddenMap.get("endTime").toString();
            String type = "hour";
            String rectifyHours = TimeUtil.transferTime(startTime,endTime,type);
            hiddenMap.put("rectifyHours",rectifyHours);
        }
    }

    public List<Map<String, Object>> getHiddenDangerListNoPage(Map<String, Object> paramsMap) {
        List<Map<String,Object>> hiddenDangerList = hiddenDangerMapper.getHiddenDangerList(paramsMap);
        if (hiddenDangerList != null && hiddenDangerList.size() > 0) {
            for (int i = 0; i < hiddenDangerList.size(); i++) {
                this.computeRectifyHours(hiddenDangerList);
            }
        }
        return hiddenDangerList;
    }

    public List<Map<String, Object>> getHiddenDangerList(Map<String, Object> params) {
        String sortColumn = "ID"; //默认的排序列
        String sortType = "DESC";
        String iSortCol_0 = (String) params.get("iSortCol_0");	//排序字段，前台传进来的为数值，列从0开始
        String sSortDir_0 = (String) params.get("sSortDir_0");	//排序类型，asc或desc
        if(StringUtil.isNotBlank(iSortCol_0) && StringUtil.isNotBlank(sSortDir_0)){
            sortColumn = (String) params.get("mDataProp_" + iSortCol_0);
            sortType = sSortDir_0;
        }
        String sortString = sortColumn + "." + sortType;	//排序字段及排序类型
        PageBounds pageBounds = new PageBounds(params, Order.formString(sortString));	//绑定排序及相关参数
        List<Map<String, Object>>  hiddenDangerList = getSqlSession().selectList("com.szgd.dao.ecdata.hiddenDanger.HiddenDangerMapper.getHiddenDangerList", params,pageBounds);
        if (hiddenDangerList != null && hiddenDangerList.size() > 0) {
            this.computeRectifyHours(hiddenDangerList);
        }
        return hiddenDangerList;
    }

    public Map<String, Object> getHiddenDanger(String id) {
        Map<String, Object> paramsMap = new HashMap<>();
        paramsMap.put("id",id);
        List<Map<String,Object>> hiddenDangerList = hiddenDangerMapper.getHiddenDangerList(paramsMap);
        if (hiddenDangerList == null || hiddenDangerList.size() == 0)
            return null;
        return hiddenDangerList.get(0);
    }


    public void insertHiddenDanger(HashMap<String, Object> paramsMap,String mFlag,String loginId,String mType,HttpServletRequest request) {
//        String theme = paramsMap.get("theme")==null?"":paramsMap.get("theme").toString();
//        Map<String,Object> tempMap = new HashMap<>();
//        tempMap.put("theme",theme);
//        int count = this.getHiddenDangerCount(tempMap);
//        if(count == 0){  //判断隐患主题是否重复
//            hiddenDangerMapper.insertHiddenDanger(paramsMap);
//            if(mFlag.equalsIgnoreCase("web")){
//                this.uploadRPorRCPic(paramsMap,loginId,mType);
//            } else if(mFlag.equalsIgnoreCase("app")){
//                this.uploadAppPic(paramsMap,request,mType);
//            }
//        }

        hiddenDangerMapper.insertHiddenDanger(paramsMap);
        if(mFlag.equalsIgnoreCase("web")){
            this.uploadRPorRCPic(paramsMap,loginId,mType);
        } else if(mFlag.equalsIgnoreCase("app")){
            this.uploadAppPic(paramsMap,request,mType);
        }

        List<String> tagList = wfRoleMapper.getTagByRole(BusinessName.hidden_danger_approver.getValue(), BusinessName.TZLX_YH.getValue());
        JpushClientUtil.sendToTagList(tagList, "站点："+paramsMap.get("siteName")+"，主题："+paramsMap.get("theme"), BusinessName.TZ_MC_YHZG.getValue(), BusinessName.TZ_MC_YHZG.getValue(), paramsMap.get("id") == null? "":paramsMap.get("id").toString());
        List<String> tagList2 = wfRoleMapper.getTagByRole(BusinessName.hidden_danger_confirmer.getValue(), BusinessName.TZLX_YH.getValue());
        JpushClientUtil.sendToTagList(tagList2, "站点："+paramsMap.get("siteName")+"，主题："+paramsMap.get("theme"), BusinessName.TZ_MC_YHQR.getValue(), BusinessName.TZ_MC_YHQR.getValue(), paramsMap.get("id") == null? "":paramsMap.get("id").toString());
    }

    public void updateHiddenDanger(HashMap<String, Object> paramsMap,String mFlag,String loginId,String mType,HttpServletRequest request) {
        hiddenDangerMapper.updateHiddenDanger(paramsMap);
        if(mFlag.equalsIgnoreCase("web")){
            this.uploadRPorRCPic(paramsMap,loginId,mType);
        } else if(mFlag.equalsIgnoreCase("app")){
            this.uploadAppPic(paramsMap,request,mType);
        }
        if(mType.equalsIgnoreCase("rectify")){
            List<String> tagList = wfRoleMapper.getTagByRole(BusinessName.hidden_danger_approver.getValue(), BusinessName.TZLX_YH.getValue());
            JpushClientUtil.sendToTagList(tagList, "站点："+paramsMap.get("siteName")+"，主题："+paramsMap.get("theme"), BusinessName.TZ_MC_YHQR.getValue(), BusinessName.TZ_MC_YHQR.getValue(), paramsMap.get("id") == null? "":paramsMap.get("id").toString());
        }else {
            List<String> tagList = wfRoleMapper.getTagByRole(BusinessName.hidden_danger_approver.getValue(), BusinessName.TZLX_YH.getValue());
            JpushClientUtil.sendToTagList(tagList, "站点："+paramsMap.get("siteName")+"，主题："+paramsMap.get("theme"),BusinessName.TZ_MC_YHZG.getValue() , BusinessName.TZ_MC_YHZG.getValue(), paramsMap.get("id") == null? "":paramsMap.get("id").toString());
            List<String> tagList2 = wfRoleMapper.getTagByRole(BusinessName.hidden_danger_confirmer.getValue(), BusinessName.TZLX_YH.getValue());
            JpushClientUtil.sendToTagList(tagList2, "站点："+paramsMap.get("siteName")+"，主题："+paramsMap.get("theme"), BusinessName.TZ_MC_YHQR.getValue(), BusinessName.TZ_MC_YHQR.getValue(), paramsMap.get("id") == null? "":paramsMap.get("id").toString());
        }

    }

    public void deleteHiddenDanger(Map<String, Object> paramsMap) {
        hiddenDangerMapper.deleteHiddenDanger(paramsMap);
    }

    public List<Map<String, Object>> getHiddenConfirmList(Map<String, Object> params) {
        return hiddenDangerMapper.getHiddenConfirmList(params);
    }

    public void confirmHidden(Map<String, Object> paramsMap) {
        hiddenDangerMapper.confirmHidden(paramsMap);
    }

    public void updRectify(Map<String, Object> paramsMap) {
        hiddenDangerMapper.updRectify(paramsMap);
    }
    
    public void updDzl(Map<String, Object> paramsMap) {
        hiddenDangerMapper.updDzl(paramsMap);
    }

    public void updReverseRectify(String yhId) {
        hiddenDangerMapper.updReverseRectify(yhId);
    }
    public void updReverseConfirm(String yhId) {
        hiddenDangerMapper.updReverseConfirm(yhId);
    }
    
    public List<Map<String, Object>> chkSendNotice(Map<String, Object> paramsMap) {
        return hiddenDangerMapper.chkSendNotice(paramsMap);
    }
    
    public List<Map<String, Object>> chkSendNoticeReverse(Map<String, Object> paramsMap) {
        return hiddenDangerMapper.chkSendNoticeReverse(paramsMap);
    }

    public List<Map<String, Object>> chkSendNoticeDzl(Map<String, Object> paramsMap) {
        return hiddenDangerMapper.chkSendNoticeDzl(paramsMap);
    }


    public void uploadRPorRCPic(HashMap<String, Object> paramMap,String loginId,String mType){
        if(mType.equalsIgnoreCase("report") || mType.equalsIgnoreCase("rectify")){
            HashMap<String, Object> uploadMap = new HashMap<>();
            String isAttachChanged = null;
            if(mType.equalsIgnoreCase("report")){
                uploadMap = (HashMap<String, Object>)paramMap.get("hiddenAttach");
                if(uploadMap != null){
                    isAttachChanged = uploadMap.get("isHiddenAttachChanged")==null?"":uploadMap.get("isHiddenAttachChanged").toString();
                }
            }else if(mType.equalsIgnoreCase("rectify")){
                uploadMap = (HashMap<String, Object>)paramMap.get("rectifyAttach");
                if(uploadMap != null){
                    isAttachChanged = uploadMap.get("isRectifyAttachChanged")==null?"":uploadMap.get("isRectifyAttachChanged").toString();
                }
            }
            if (isAttachChanged != null && isAttachChanged.equalsIgnoreCase("1")) {
                String parentId = uploadMap.get("parentId")== null?"":uploadMap.get("parentId").toString().replace("null","");
                if (parentId.length() == 0) {
                    uploadMap.put("parentId", paramMap.get("id"));
                }
                uploadMap.put("creator",loginId);
                uploadMap.put("uploader",loginId);
                attachService.saveAttach(uploadMap);
            }
        }
    }

    public void uploadAppPic(HashMap<String, Object> paramMap,HttpServletRequest request,String mType){
        if(mType.equalsIgnoreCase("report") || mType.equalsIgnoreCase("rectify")){
            String picName = weChatService.uploadPic(request);
            HashMap<String,Object> attachMap = new HashMap<>();
            if(mType.equalsIgnoreCase("report")){
                attachMap.put("parentId",paramMap.get("id"));
                attachMap.put("name",picName);
                attachMap.put("type","ATTACH_PIC");
                attachMap.put("source","ATTACH_DANGER");
            }else if(mType.equalsIgnoreCase("rectify")){
                attachMap.put("id",paramMap.get("rectifyAttachId"));
                attachMap.put("parentId",paramMap.get("id"));
                attachMap.put("name",picName);
                attachMap.put("type","ATTACH_PIC");
                attachMap.put("source","ATTACH_DANGER_RECTIFY");
            }
            if(picName.length() > 0){
                attachService.saveAttach(attachMap);
            }
        }
    }

    public Map<String, String> getDownlaodMap(){
        Map<String, String> fieldMapping = new LinkedHashMap<>();

        fieldMapping.put("number","编号");
        fieldMapping.put("theme","隐患主题");
        fieldMapping.put("rectifyDeadline","整改期限(天)");
        fieldMapping.put("bidName","标段");
        fieldMapping.put("siteName","车站");
        fieldMapping.put("reportPersonName","上报人");
        fieldMapping.put("rectifyBeginTime","上报时间");
        fieldMapping.put("findTime","隐患发现时间");
        fieldMapping.put("description","隐患描述");

        fieldMapping.put("rectifyPersonName","整改人");
        fieldMapping.put("rectifyTime","整改时间");
        fieldMapping.put("rectifyContent","整改内容");

        fieldMapping.put("confirmerName","确认人");
        fieldMapping.put("rectifyEndTime","确认时间");
        fieldMapping.put("confirmAdvice","确认意见");

        return fieldMapping;
    }

    public Map<String, String> getFieldMap(){
        Map<String, String> fieldMapping = new LinkedHashMap<>();

        fieldMapping.put("number","编号");
        fieldMapping.put("theme","隐患主题");
        fieldMapping.put("rectifyDeadline","整改期限(天)");
        fieldMapping.put("bidName","标段");
        fieldMapping.put("siteId","车站");
        fieldMapping.put("reportPerson","上报人");
        fieldMapping.put("rectifyBeginTime","上报时间");
        fieldMapping.put("findTime","隐患发现时间");
        fieldMapping.put("description","隐患描述");

        fieldMapping.put("rectifyPerson","整改人");
        fieldMapping.put("rectifyTime","整改时间");
        fieldMapping.put("rectifyContent","整改内容");

        fieldMapping.put("confirmer","确认人");
        fieldMapping.put("rectifyEndTime","确认时间");
        fieldMapping.put("confirmAdvice","确认意见");

        return fieldMapping;
    }

    public Map<String, Object> batchImportExcel(List<Map<String, Object>> infoList,String userId,String batchNo) {
        Map<String, Object> resultMap = new HashMap<>();
        List<Map<String, Object>> successList = new ArrayList<>();   //记录导入成功的数据
        List<Map<String, Object>> updateList = new ArrayList<>();   //记录更新的数据
        List<Map<String, Object>> failedList = new ArrayList<>();   //记录导入失败的数据
        List<Map<String, Object>> ignoreList = new ArrayList<>();   //记录忽略的数据

        for (Map<String, Object> infoMap : infoList) {

            HashMap<String, Object> sourceDataMap = new HashMap<String, Object>(infoMap);
            try {

                //判断必填项
                if(infoMap.get("number") != null && StringUtil.isNotBlank(String.valueOf(infoMap.get("number")))) {

                }else{
                    sourceDataMap.put("ERROR_MSG","编号为必填项");
                    failedList.add(sourceDataMap);
                    continue;
                }
                if(infoMap.get("theme") != null && StringUtil.isNotBlank(String.valueOf(infoMap.get("theme")))) {

                }else{
                    sourceDataMap.put("ERROR_MSG","隐患主题为必填项");
                    failedList.add(sourceDataMap);
                    continue;
                }
                if(infoMap.get("rectifyDeadline") != null && StringUtil.isNotBlank(String.valueOf(infoMap.get("rectifyDeadline")))) {
                }else{
                    sourceDataMap.put("ERROR_MSG","整改期限为必填项");
                    failedList.add(sourceDataMap);
                    continue;
                }
                if(infoMap.get("siteId") != null && StringUtil.isNotBlank(String.valueOf(infoMap.get("siteId")))) {
                }else{
                    sourceDataMap.put("ERROR_MSG","车站为必填项");
                    failedList.add(sourceDataMap);
                    continue;
                }
                if(infoMap.get("reportPerson") != null && StringUtil.isNotBlank(String.valueOf(infoMap.get("reportPerson")))) {
                }else{
                    sourceDataMap.put("ERROR_MSG","上报人为必填项");
                    failedList.add(sourceDataMap);
                    continue;
                }
                if(infoMap.get("rectifyBeginTime") != null && StringUtil.isNotBlank(String.valueOf(infoMap.get("rectifyBeginTime")))) {
                }else{
                    sourceDataMap.put("ERROR_MSG","上报时间为必填项");
                    failedList.add(sourceDataMap);
                    continue;
                }
                if(infoMap.get("findTime") != null && StringUtil.isNotBlank(String.valueOf(infoMap.get("findTime")))) {
                }else{
                    sourceDataMap.put("ERROR_MSG","隐患发现时间为必填项");
                    failedList.add(sourceDataMap);
                    continue;
                }
                if(infoMap.get("description") != null && StringUtil.isNotBlank(String.valueOf(infoMap.get("description")))) {
                }else{
                    sourceDataMap.put("ERROR_MSG","隐患描述为必填项");
                    failedList.add(sourceDataMap);
                    continue;
                }

                //判断整改期限是否为数字
                if(infoMap.get("rectifyDeadline") != null && StringUtil.isNotBlank(String.valueOf(infoMap.get("rectifyDeadline")))) {
                    String rectifyDeadline = infoMap.get("rectifyDeadline").toString();
                    boolean res = NumberValidation.isInteger(rectifyDeadline);
                    if(res == false){
                        sourceDataMap.put("ERROR_MSG","整改期限填写不正确(必须为数字)");
                        failedList.add(sourceDataMap);
                        continue;
                    }
                }

                //判断车站是否填写正确
                if(infoMap.get("siteId") != null && StringUtil.isNotBlank(String.valueOf(infoMap.get("siteId")))) {
                    infoMap.put("siteName", infoMap.get("siteId"));
                    List<Map<String,Object>> siteList = siteService.getSiteListNoPage(infoMap);
                    if (siteList != null && siteList.size() > 0) {
                        Map<String,Object> siteMap = siteList.get(0);
                        infoMap.put("siteId", siteMap.get("id"));
                    } else {
                        sourceDataMap.put("ERROR_MSG","车站填写不正确(参考站点管理)");
                        failedList.add(sourceDataMap);
                        continue;
                    }
                }

                //判断上报人是否填写正确
                if(infoMap.get("reportPerson") != null && StringUtil.isNotBlank(String.valueOf(infoMap.get("reportPerson")))) {
                    infoMap.put("userName", infoMap.get("reportPerson"));
                    List<Map<String,String>> userList = userService.getAllUserInfo(infoMap);
                    if (userList != null && userList.size() > 0) {
                        Map<String,String> userMap = userList.get(0);
                        infoMap.put("reportPerson", userMap.get("USER_ID"));
                    } else {
                        sourceDataMap.put("ERROR_MSG","上报人填写不正确(参考用户管理)");
                        failedList.add(sourceDataMap);
                        continue;
                    }
                }

                //判断上报时间
                if(infoMap.get("rectifyBeginTime") != null && StringUtil.isNotBlank(String.valueOf(infoMap.get("rectifyBeginTime")))) {
                    String rectifyBeginTime = infoMap.get("rectifyBeginTime").toString();
                    boolean res = TimeUtil.isValidDateToMin(rectifyBeginTime);
                    if(res == false){
                        sourceDataMap.put("ERROR_MSG","上报时间填写不正确(格式YYYY-MM-DD HH:MM)");
                        failedList.add(sourceDataMap);
                        continue;
                    }
                }

                //判断隐患发现时间
                if(infoMap.get("findTime") != null && StringUtil.isNotBlank(String.valueOf(infoMap.get("findTime")))) {
                    String findTime = infoMap.get("findTime").toString();
                    boolean res = TimeUtil.isValidDate(findTime);
                    if(res == false){
                        sourceDataMap.put("ERROR_MSG","隐患发现时间填写不正确(格式YYYY-MM-DD)");
                        failedList.add(sourceDataMap);
                        continue;
                    }
                }

                Map<String, Object> paramMap = new HashMap<String, Object>();
                paramMap.put("number",infoMap.get("number"));
                List<Map<String, Object>> hiddenDangerList = this.getHiddenDangerListNoPage(paramMap);
                if (hiddenDangerList != null && hiddenDangerList.size() > 0)
                {
                    sourceDataMap.put("ERROR_MSG","数据库中已存在该编号，请重新命名编号");
                    failedList.add(sourceDataMap);
                    continue;
                } else {
                    infoMap.put("creator",userId);
                    infoMap.put("status","REPORT");
                    hiddenDangerMapper.insertHiddenDanger(infoMap);
                    successList.add(infoMap);
                }

            }catch (Exception e){
                String errorMsg = e.getMessage();
                if(errorMsg.indexOf("###",10) != -1){
                    errorMsg = errorMsg.substring(0,errorMsg.indexOf("###",10));
                }
                sourceDataMap.put("ERROR_MSG",errorMsg);
                //记录导入失败记录
                failedList.add(sourceDataMap);
            }
        }

        //组装本次导入的结果
        resultMap.put(Constant.IMPORT_HE_SUCCESS,successList);
        resultMap.put(Constant.IMPORT_HE_IGNORE,ignoreList);
        resultMap.put(Constant.IMPORT_HE_FAILED,failedList);
        resultMap.put(Constant.IMPORT_HE_UPDATED,updateList);
        return resultMap;
    }

    public String uploadReportPic(HiddenDanger hiddenDanger) throws Exception {
        String message = "";
        int allNum = 0;
        int successNum = 0;
        int errorNum = 0;
        List<String> errorMsg = new ArrayList<>();
        if(hiddenDanger != null){
            if(hiddenDanger.getPicAttach() != null){
                Map<String,Object> queryParam = new HashMap<>();
                Map<String,Object> attachParam = new HashMap<>();
                attachParam.put("source","ATTACH_DANGER");
                attachParam.put("type","ATTACH_PIC");
                attachParam.put("creator",hiddenDanger.getCreator());
                attachParam.put("path",SysUtil.getDateStr(null,"yyyyMM"));
                for(MultipartFile file : hiddenDanger.getPicAttach()){
                    allNum += 1;
                    String originalFileName = file.getOriginalFilename();
                    int index =  originalFileName.lastIndexOf(".");
                    String fileName = originalFileName.substring(0,index);
                    queryParam.put("number",fileName);
                    List<Map<String,Object>> hiddenList = this.getHiddenDangerListNoPage(queryParam);
                    if(hiddenList != null && hiddenList.size() > 0){
                        if(hiddenList.size() == 1){
                            try{
                                String attachName = fileUtil.uploadPic(file.getInputStream(),originalFileName);
                                attachParam.put("name",attachName);
                                String id = hiddenList.get(0).get("id")==null?"":hiddenList.get(0).get("id").toString();
                                String attachId = hiddenList.get(0).get("attachId")==null?"":hiddenList.get(0).get("attachId").toString();
                                String status = hiddenList.get(0).get("status")==null?"":hiddenList.get(0).get("status").toString();
                                String statusName = hiddenList.get(0).get("statusName")==null?"":hiddenList.get(0).get("statusName").toString();
                                if(status.equalsIgnoreCase("REPORT")){
                                    if(attachId.length() > 0){
                                        attachParam.put("parentId",id);
                                        attachParam.put("id",attachId);
                                        attachService.deleteAttach(attachParam);
                                        attachService.insertAttach(attachParam);
                                    }else{
                                        attachParam.put("parentId",id);
                                        attachService.insertAttach(attachParam);
                                    }
                                    successNum += 1;
                                }else{
                                    errorNum += 1;
                                    errorMsg.add(originalFileName + "的隐患的状态为" + statusName + "，无法上传隐患照片");
                                }
                            }catch (Exception e){
                                errorNum += 1;
                                errorMsg.add(originalFileName + "上传失败，服务器出错");
                            }
                        }else{
                            errorNum += 1;
                            errorMsg.add(originalFileName + "的隐患编号在数据库中存在重复现象，请手动上传相关隐患");
                        }
                    }else{
                        errorNum += 1;
                        errorMsg.add(originalFileName + "的隐患在数据库中不存在，请检查命名是否准确");
                    }
                }
                message += "本次上传共处理<b>" + allNum
                        + "张</b>照片[<span style = 'color: green;font-weight: bold;'>成功："
                        + successNum + "张</span>，<span style = 'color: red;font-weight: bold;'>失败：" + errorNum + "张</span>]";
                if(errorNum > 0){
                    message += "</br><span style = 'font-weight: bold;'>失败条目如下：</span></br>";
                    for(int i = 0; i < errorMsg.size(); i++){
                        message += (i+1) + ". " + errorMsg.get(i) + "</br>";
                    }
                }

            }
        }
        return message;
    }

    public Map<String, Object> batchImportRectifyExcel(List<Map<String, Object>> infoList,String userId,String batchNo) {
        Map<String, Object> resultMap = new HashMap<>();
        List<Map<String, Object>> successList = new ArrayList<>();   //记录导入成功的数据
        List<Map<String, Object>> updateList = new ArrayList<>();   //记录更新的数据
        List<Map<String, Object>> failedList = new ArrayList<>();   //记录导入失败的数据
        List<Map<String, Object>> ignoreList = new ArrayList<>();   //记录忽略的数据

        for (Map<String, Object> infoMap : infoList) {
            Map<String, Object> tempMap = new HashMap<>();

            HashMap<String, Object> sourceDataMap = new HashMap<String, Object>(infoMap);
            try {

                //判断必填项
                if(infoMap.get("rectifyPerson") != null && StringUtil.isNotBlank(String.valueOf(infoMap.get("rectifyPerson")))) {

                }else{
                    sourceDataMap.put("ERROR_MSG","整改人为必填项");
                    failedList.add(sourceDataMap);
                    continue;
                }
                if(infoMap.get("rectifyTime") != null && StringUtil.isNotBlank(String.valueOf(infoMap.get("rectifyTime")))) {
                }else{
                    sourceDataMap.put("ERROR_MSG","整改时间为必填项");
                    failedList.add(sourceDataMap);
                    continue;
                }

                //判断整改人是否填写正确
                if(infoMap.get("rectifyPerson") != null && StringUtil.isNotBlank(String.valueOf(infoMap.get("rectifyPerson")))) {
                    infoMap.put("userName", infoMap.get("rectifyPerson"));
                    List<Map<String,String>> userList = userService.getAllUserInfo(infoMap);
                    if (userList != null && userList.size() > 0) {
                        Map<String,String> userMap = userList.get(0);
                        tempMap.put("rectifyPerson",userMap.get("USER_ID"));
                    } else {
                        sourceDataMap.put("ERROR_MSG","整改人填写不正确(参考用户管理)");
                        failedList.add(sourceDataMap);
                        continue;
                    }
                }

                //判断整改时间
                if(infoMap.get("rectifyTime") != null && StringUtil.isNotBlank(String.valueOf(infoMap.get("rectifyTime")))) {
                    String rectifyTime = infoMap.get("rectifyTime").toString();
                    boolean res = TimeUtil.isValidDateToMin(rectifyTime);
                    if(res == false){
                        sourceDataMap.put("ERROR_MSG","整改时间填写不正确(格式YYYY-MM-DD HH:MM)");
                        failedList.add(sourceDataMap);
                        continue;
                    }else{
                        tempMap.put("rectifyTime",infoMap.get("rectifyTime"));
                    }
                }


                Map<String, Object> paramMap = new HashMap<String, Object>();
                paramMap.put("number",infoMap.get("number"));
                List<Map<String, Object>> hiddenDangerList = this.getHiddenDangerListNoPage(paramMap);
                if (hiddenDangerList != null && hiddenDangerList.size() > 0)
                {
                    if(hiddenDangerList.size() == 1){
                        tempMap.put("rectifyContent",infoMap.get("rectifyContent"));
                        tempMap.put("creator",userId);
                        tempMap.put("id",hiddenDangerList.get(0).get("id"));
                        tempMap.put("status","RECTIFY");
                        hiddenDangerMapper.updateHiddenDanger(tempMap);
                        updateList.add(infoMap);
                    } else{
                        sourceDataMap.put("ERROR_MSG","数据库中存在多条以该隐患编号命名的重复隐患，请手动上传相关隐患的照片");
                        failedList.add(sourceDataMap);
                        continue;
                    }
                } else {
                    sourceDataMap.put("ERROR_MSG","该隐患还未上报");
                    failedList.add(sourceDataMap);
                    continue;
                }

            }catch (Exception e){
                String errorMsg = e.getMessage();
                if(errorMsg.indexOf("###",10) != -1){
                    errorMsg = errorMsg.substring(0,errorMsg.indexOf("###",10));
                }
                sourceDataMap.put("ERROR_MSG",errorMsg);
                //记录导入失败记录
                failedList.add(sourceDataMap);
            }
        }

        //组装本次导入的结果
        resultMap.put(Constant.IMPORT_HE_SUCCESS,successList);
        resultMap.put(Constant.IMPORT_HE_IGNORE,ignoreList);
        resultMap.put(Constant.IMPORT_HE_FAILED,failedList);
        resultMap.put(Constant.IMPORT_HE_UPDATED,updateList);
        return resultMap;
    }

    public String uploadRectifyPic(HiddenDanger hiddenDanger) throws Exception {
        String message = "";
        int allNum = 0;
        int successNum = 0;
        int errorNum = 0;
        List<String> errorMsg = new ArrayList<>();
        if(hiddenDanger != null){
            if(hiddenDanger.getPicAttach() != null){
                Map<String,Object> queryParam = new HashMap<>();
                Map<String,Object> attachParam = new HashMap<>();
                attachParam.put("source","ATTACH_DANGER_RECTIFY");
                attachParam.put("type","ATTACH_PIC");
                attachParam.put("creator",hiddenDanger.getCreator());
                attachParam.put("path",SysUtil.getDateStr(null,"yyyyMM"));
                for(MultipartFile file : hiddenDanger.getPicAttach()){
                    allNum += 1;
                    String originalFileName = file.getOriginalFilename();
                    int index =  originalFileName.lastIndexOf(".");
                    String fileName = originalFileName.substring(0,index);
                    queryParam.put("number",fileName);
                    List<Map<String,Object>> hiddenList = this.getHiddenDangerListNoPage(queryParam);
                    if(hiddenList != null && hiddenList.size() > 0){
                        if(hiddenList.size() == 1){
                            try{
                                String attachName = fileUtil.uploadPic(file.getInputStream(),originalFileName);
                                attachParam.put("name",attachName);
                                String id = hiddenList.get(0).get("id")==null?"":hiddenList.get(0).get("id").toString();
                                String rectifyAttachId = hiddenList.get(0).get("rectifyAttachId")==null?"":hiddenList.get(0).get("rectifyAttachId").toString();
                                String status = hiddenList.get(0).get("status")==null?"":hiddenList.get(0).get("status").toString();
                                String statusName = hiddenList.get(0).get("statusName")==null?"":hiddenList.get(0).get("statusName").toString();
                                if(!status.equalsIgnoreCase("CONFIRM")){
                                    if(rectifyAttachId.length() > 0){
                                        attachParam.put("parentId",id);
                                        attachParam.put("id",rectifyAttachId);
                                        attachService.deleteAttach(attachParam);
                                        attachService.insertAttach(attachParam);
                                    }else{
                                        attachParam.put("parentId",id);
                                        attachService.insertAttach(attachParam);
                                    }
                                    successNum += 1;
                                }else{
                                    errorNum += 1;
                                    errorMsg.add(originalFileName + "的隐患的状态为" + statusName + "，无法上传隐患照片");
                                }
                            }catch (Exception e){
                                errorNum += 1;
                                errorMsg.add(originalFileName + "上传失败，服务器出错");
                            }
                        }else{
                            errorNum += 1;
                            errorMsg.add(originalFileName + "的隐患编号在数据库中存在重复现象，请手动上传相关隐患的照片");
                        }
                    }else{
                        errorNum += 1;
                        errorMsg.add(originalFileName + "的隐患在数据库中不存在，请检查命名是否准确");
                    }
                }
                message += "本次上传共处理<b>" + allNum
                        + "张</b>照片[<span style = 'color: green;font-weight: bold;'>成功："
                        + successNum + "张</span>，<span style = 'color: red;font-weight: bold;'>失败：" + errorNum + "张</span>]";
                if(errorNum > 0){
                    message += "</br><span style = 'font-weight: bold;'>失败条目如下：</span></br>";
                    for(int i = 0; i < errorMsg.size(); i++){
                        message += (i+1) + ". " + errorMsg.get(i) + "</br>";
                    }
                }

            }
        }
        return message;
    }

    public List<Map<String, Object>> getAppHiddenDangerList(Map<String, Object> paramsMap) {
        List<Map<String,Object>> hiddenDangerList = hiddenDangerMapper.getAppHiddenDangerList(paramsMap);
        return hiddenDangerList;
    }

    public List<Map<String,Object>> getAppHiddenDangerCount(Map<String, Object> paramsMap){
        return hiddenDangerMapper.getAppHiddenDangerCount(paramsMap);
    }
}
